using System;
using System.Globalization;

using Android.Views;

using Outcoder.UI.Xaml.Data;

namespace Outcoder.UI.Xaml.ValueConverters
{
	public class BooleanToVisibilityConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			string paramValue = (string)parameter ?? string.Empty;
			paramValue = paramValue.Trim();

			bool goneWhenTrue = string.Compare(paramValue, "gone", StringComparison.OrdinalIgnoreCase) == 0
				|| string.Compare(paramValue, "collapsed", StringComparison.OrdinalIgnoreCase) == 0;

			bool invisibleWhenTrue = false;

			if (!goneWhenTrue)
			{
				invisibleWhenTrue = string.Compare(
					paramValue, "invisible", StringComparison.OrdinalIgnoreCase) == 0;
			}


			if (value == null || (bool)value)
			{
				if (goneWhenTrue)
				{
					return ViewStates.Gone;
				}

				if (invisibleWhenTrue)
				{
					return ViewStates.Invisible;
				}

				return ViewStates.Visible;
			}

			/* value is false. */

			if (goneWhenTrue || invisibleWhenTrue)
			{
				return ViewStates.Visible;
			}

			return ViewStates.Gone;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			string paramValue = (string)parameter ?? string.Empty;

			bool goneWhenTrue = string.Compare(paramValue, "gone", StringComparison.OrdinalIgnoreCase) == 0
							|| string.Compare(paramValue, "collapsed", StringComparison.OrdinalIgnoreCase) == 0;

			bool invisibleWhenTrue = false;

			if (!goneWhenTrue)
			{
				invisibleWhenTrue = string.Compare(
					paramValue, "invisible", StringComparison.OrdinalIgnoreCase) == 0;
			}

			if (value == null || (ViewStates)value == ViewStates.Visible)
			{
				return !(goneWhenTrue || invisibleWhenTrue);
			}

			return goneWhenTrue || invisibleWhenTrue;
		}
	}
}